module pflanza.materials;

import std.stream;
import utils.configfile;
import utils.color;

enum MaterialType {
    matColor,
    matTexture,
}

struct Material {
    MaterialType type;
    char[] texFile;
    RGBColor col;

    public static Material opCall(ConfigNode matNode) {
        Material ret;
        if (matNode.exists("texture")) {
            ret.texFile = matNode.getStringValue("texture","");
            ret.type = MaterialType.matTexture;
        } else if (matNode.exists("color")) {
            ConfigNode colNode = matNode.getSubNode("color",false);
            ret.col.r = colNode.getFloatValue("r",0);
            ret.col.g = colNode.getFloatValue("g",0);
            ret.col.b = colNode.getFloatValue("b",0);
            ret.type = MaterialType.matColor;
        } else {
            throw new Exception("Invalid material definition");
        }
        return ret;
    }

    public void writeScript(char[] id, Stream st) {
        st.writefln("newmat simple %s",id);
        switch (type) {
            case MaterialType.matTexture:
                st.writefln("mattex 0 %s",texFile);
                break;
            case MaterialType.matColor:
                st.writefln("matcolor 0 %f %f %f",col.r,col.g,col.b);
                break;
            default:
                break;
        }
    }
}

class Materials {
    private {
        Material[char[]] mMaterials;
    }

    public void fromNode(ConfigNode matsNode) {
        foreach (char[] id, ConfigNode n; matsNode) {
            mMaterials[id] = Material(n);
        }
    }

    public void writeScript(Stream st) {
        st.writefln("# Materials");
        foreach (char[] id, Material m; mMaterials) {
            m.writeScript(id,st);
        }
    }
}
